<?php

namespace app\admin\controller;

use app\admin\model\StudentModel;
use app\admin\model\ResultModel;
use app\admin\model\SubjectModel;
use cmf\controller\AdminBaseController;
use think\Controller;
use think\Request;
use think\Db;
use think\db\Query;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ResultController extends AdminBaseController
{
    public function index()
    {
        $name=$this->request->param('name');
        $result=Db::name('result')->join('cmf_student','cmf_student.id=cmf_result.student_id','LEFT')
            ->join('cmf_subject','cmf_subject.id=cmf_result.subject_id','LEFT')
            ->field('cmf_result.*,cmf_student.name as student_name,cmf_subject.name as subject_name')

            ->where(function (Query $query) use ($name){
                if ($name){
                    $query->where('cmf_student.name','like',"%$name%");
                }
            })
            ->order('id desc')
            ->paginate(2,false,$this->request->param());
        $page=$result->render();
        return $this->fetch('',['page'=>$page,'result'=>$result]);
    }
    public function add()
    {
        $student=StudentModel::select();
        $result=resultModel::select();
        $subject=SubjectModel::select();
        return $this->fetch('add',['student'=>$student,'result'=>$result,'subject'=>$subject]);
    }
    public function addTwo(){
        $data=input();
        $add=Db::name('result')->insert($data);
        if ($add){
            $this->success('添加成功','result/index');
        }else{
            $this->error('添加失败');
        }
    }
    public function edit()
    {
        $id = input('id');
        $result = ResultModel::get($id);
        $subject = SubjectModel::all();
        $student = StudentModel::all();
        return $this->fetch('', [
            'result ' => $result ,
            'subject'=>$subject,
            'student' => $student
        ]);

    }
    public function editPost()
    {
        $data = input();
        $edit=ResultModel::update($data,['id'=>$data['id']]);
        if ($edit) {
            $this->success("修改成功！", "result/index");
        }else{
            $this->error("修改失败！");
        }
    }
    public function cj($id){
        $result=Db::name('result')
            ->join('cmf_student','cmf_student.id=cmf_result.student_id')
            ->join('cmf_subject','cmf_subject.id=cmf_result.subject_id')
            ->field('cmf_result.*,cmf_student.name as student_name,cmf_subject.name as subject_name')
            ->where('cmf_result.id',$id)
            ->select();
        //halt($result);
       return view('',['result'=>$result]);
    }
    public function delete($id)
    {
        $del=ResultModel::destroy($id);
        if ($del){
            $this->success('删除成功','result/index');
        }else{
            $this->error('删除失败');
        }
    }
    public function exportExcel()
    {
        // 查询要导出的数据 room=subject  school=student
        $data = Db::name('result')
            ->join('cmf_student','cmf_student.id=cmf_result.student_id','LEFT')
            ->join('cmf_subject','cmf_subject.id=cmf_result.subject_id','LEFT')
            ->field('cmf_result.*,cmf_student.name as student_name,cmf_subject.name as subject_name')
            ->select();
        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学生姓名');
        $sheet->getColumnDimension('B')->setWidth(10);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('科目');
        $sheet->getColumnDimension('C')->setWidth(10);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('成绩');
        $sheet->getColumnDimension('D')->setWidth(10);


        // 设置样式 标题
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);

        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['student_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['subject_name']);

            $cellD = $sheet->getCell('D'.$n);
            $cellD->setValue($v['result']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('D'.$n)->applyFromArray($styleArrayBody);
        }

        $file_name = 'resultExcel.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    public function importExcel(){
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取总列数
        //$highestColumn = $sheet->getHighestColumn();
        // 获取总行数
        $highestRow = $sheet->getHighestRow();
        // 将列转为数字
        //$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 3 列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $student_name = $sheet->getCellByColumnAndRow(3,$i)->getValue();
            $subject_name = $sheet->getCellByColumnAndRow(5,$i)->getValue();
            $result = $sheet->getCellByColumnAndRow(4,$i)->getValue();
            $data = [
                'student_name' => $student_name,
                'subject_name' => $subject_name,
                'result' => $result,
            ];
            $insert = Db::name('result')->insert($data);
            if ($insert) {
                $successLog[] = '第'.$i.'条，插入成功';
            } else {
                $failLog[] = '第'.$i.'条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
    public function download(){
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学生姓名');
        $sheet->getColumnDimension('B')->setWidth(10);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('科目');
        $sheet->getColumnDimension('C')->setWidth(10);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('成绩');
        $sheet->getColumnDimension('D')->setWidth(10);


        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);


        // 从 A2 开始填充数据
        // 获取单元格
        $cellA = $sheet->getCell('A2');
        // 设置单元格的值
        $cellA->setValue(1);

        $cellB = $sheet->getCell('B2');
        $cellB->setValue('学生');

        $cellC = $sheet->getCell('C2');
        $cellC->setValue('张三');

        $cellD = $sheet->getCell('D2');
        $cellD->setValue(1);


        // 再给表格体设置样式
        $sheet->getStyle('A2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('B2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('C2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('D2')->applyFromArray($styleArrayBody);

        $file_name = 'down.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}
